const commonUtil = require('../../util/common');

module.exports = (componentName = '') => {
  // 驼峰组件名
  const H_T_C_N = commonUtil.upperFirst(componentName);

  return `
<template>
  <BasicDrawer
    v-bind="$attrs"
    width="40%"
    show-footer
    destroy-on-close
    :title="getTitle"
    @register="registerDrawer"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm" />
  </BasicDrawer>
</template>
<script lang="ts">
  import { computed, defineComponent, ref, unref } from 'vue';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { formSchema } from './${componentName}.data';
  import { update${H_T_C_N} } from '/@/api/${componentName}';
  import { message } from 'ant-design-vue';

  export default defineComponent({
    components: { BasicDrawer, BasicForm },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const isUpdate = ref(true);

      const [registerForm, { setFieldsValue, resetFields, validate, getFieldsValue }] = useForm({
        labelWidth: 100,
        schemas: formSchema,
        showActionButtonGroup: false,
        baseColProps: {
          span: 12,
        },
        actionColOptions: {
          span: 23,
        },
      });

      const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
        resetFields();
        setDrawerProps({ confirmLoading: false });
        isUpdate.value = !!data?.isUpdate;

        if (unref(isUpdate)) {
          setFieldsValue({
            ...data.record,
          });
        }

      });

      const getTitle = computed(() => (!unref(isUpdate) ? '新增$1' : '编辑$1'));

      async function handleSubmit() {
        try {
          await validate();
          setDrawerProps({ confirmLoading: true });
          const values = getFieldsValue();
          // TODO custom api
          await update${H_T_C_N}(values);
          message.success('操作成功');
          closeDrawer();
          emit('success', {
            isUpdate: unref(isUpdate),
            values: { ...values, id: values.id },
          });
        } finally {
          setDrawerProps({ confirmLoading: false });
        }
      }

      return { registerDrawer, registerForm, getTitle, handleSubmit };
    },
  });
</script>
`;
};
